var secretOrPrivateKey = "This is perfect projects.";
var adminPrivateKey = "admin projects.";
const Token = require("./Token");
const { User } = require("./../models");
const md5 = require("md5");
module.exports = async function (req, res, next) {
  // 获取请求头中的Authorization认证字符
  if (/login/.test(req.path)) {
    next();
  } else if (/regist/.test(req.path)) {
    next();
  } else if (/getSystemParams/.test(req.path)) {
    next();
  } else if (/updatePassword/.test(req.path)) {
    next();
  } else if (/article\/findArticle/.test(req.path)) {
    next();
  } else if (/article\/findAllLabel/.test(req.path)) {
    next();
  } else if (/article\/findArticleById/.test(req.path)) {
    next();
  } else if (/comment\/findComment/.test(req.path)) {
    next();
  } else if (/uploads\/imgs/.test(req.path)) {
    next();
  } else {
    // 不需要token的接口
    if (req.get("Authorization") == null) {
      return res.sendResult(null, 403, "用户没有登录");
    } else {
      let authorization = req.get("Authorization").split(" ")[1];
      let data = Token.decrypt(authorization, secretOrPrivateKey);

      if (data.token) {
        const { username, password } = data.data;
        try {
          let user = await User.findOne({
            where: {
              username,
              password: md5(password),
            },
          });
          if (username != "xinkai") {
            if (
              req.path.includes("createArticle") ||
              req.path.includes("deleteArticle") ||
              req.path.includes("editArticle") ||
              req.path.includes("deleteUser") ||
              req.path.includes("files") ||
              req.path.includes("edit") ||
              req.path.includes("upload") ||
              req.path.includes("addDownload")
            ) {
              return res.sendResult(null, 403, "您没有权限进行操作");
            }
          }
          req.query.user = user.dataValues;
          return next();
        } catch (error) {
          return res.sendStatus(403);
        }
        //有效toke
      } else {
        return res.sendStatus(403);
      }
    }
  }
};
